var http = require('http');
var url = require('url');
var fs = require('fs');
var cookieSession = require('cookie-session');
var controller = require('./controller');
var apiController = require('./apiController');
var PORT = 8021;

var session = cookieSession({
  name: 'weibo-api',
  keys: ['key1']
});

var server = http.createServer(function (req, res) {
  session(req, res, function () {
    var pathname = url.parse(req.url).pathname;
    // console.log('pathname', pathname);
    if (pathname.indexOf('/static/') === 0) {
      fs.readFile(__dirname + pathname, 'binary', function (err, data) {
        // console.log('readFile', err);
        if (err) {
          render(res, 404, (pathname + ' not be found'));
        } else {
          showFile(res, 'image/png', data);
        }
      });
      return;
    } else if (pathname.indexOf('/api/') === 0) {
      checkToken(req, res, function () {
        var action = pathname.replace('/api/', '');
        if (typeof apiController[action] == 'function') {
          apiController[action](req, res);
        } else {
          render(res, 404, (pathname + ' not be found'));
        }
      });
      return;
    }
    var action = pathname.replace('/', '');
    if (typeof controller[action] == 'function') {
      controller[action](req, res);
    } else {
      render(res, 404, (pathname + ' not be found'));
    }
  });
});

server.listen(PORT, function (obj) {
  console.log('Server has started at port:' + PORT);
});


function checkToken (req, res, next) {
  if (req.session.access_token) {
    next();
  } else {
    json(res, {
      error: 'need acess token',
      data: null
    });
  }
}


function json (res, obj) {
  res.writeHead(200, {
    'Content-Type': 'application/json; charset=utf-8'
  });
  res.write(JSON.stringify(obj));
  res.end();
}


function render (res, code, content) {
  res.writeHead(code, {
    'Content-Type': 'text/html; charset=utf-8'
  });
  var header = '<!DOCTYP html><html><head><meta charset="utf-8"></head><body>';
  var footer = '</body></html>';
  res.write(header + content + footer);
  res.end();
}


function showFile (res, type, data) {
  res.writeHead(200, {
    'Content-Type': type
  });
  res.write(data, 'binary');
  res.end();
}
